package collection;

/**
 * 自定义一个链表
 */
public class MyLinkList01<E> {
    private Node first;
    private Node last;
    int size;

    public void add(E element){
        Node node = new Node(element);
        if(first==null){//第一次放
            first =node;
            last = node;
        }else{
            node.pre = last;
            node.next = null;

            last.next=node;
            last=node;
        }
        size++;
    }

    //重写toString来获取值
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
      Node temp = first;
      while (temp!=null){
          sb.append(temp.element+",");
          temp=temp.next;
      }
      sb.setCharAt(sb.length()-1,']');
      return  sb.toString();
    }

  //根据索引获取Node
    public Node getNode(int index){
        checkRange(index);
        Node temp = null;
        if(index<=size>>1){//提高效率
            temp = first;
            for (int i=0;i<index;i++){
                temp = temp.next;
            }
        }else{
            temp = last;
            for(int i=size-1;i<index;i--){
                temp = temp.pre;
            }
        }
        return temp;
    }

    //get
    public E get(int index){
        checkRange(index);
        Node temp=getNode(index);

        return temp!=null?(E)temp.element:null;
    }

    //remove
    public void remove(int index){
        checkRange(index);
        Node temp =getNode(index);
        if(temp!=null){
            Node up = temp.pre;
            Node down = temp.next;

            if(up!=null){
                up.next=down;
            }
            if (down!=null){
                down.pre=up;
            }
            if(index==0){//第一个
                first = down;
            }
            if(index == size-1){//最后一个

                last = up;
            }
            size--;
        }
    }

    //插入节点
    public void add(int index,E element){
        checkRange(index);
        Node temp =  getNode(index);
        Node newNode = new Node(element);
        if(temp!=null){
            Node up = temp.pre;

            up.next=newNode;
            newNode.pre=up;

            temp.pre=newNode;
            newNode.next=temp;
        }
        size++;
    }

    //索引判断
    private void checkRange(int index){
        if(index<0||index>size-1){
            throw new RuntimeException("索引数字不合法");
        }
    }

    public static void main(String[] args) {
        MyLinkList01<String> list = new MyLinkList01<>();
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println(list.get(2));
        System.out.println(list);
        list.remove(2);
        System.out.println(list);
        list.add(1,"x");
        System.out.println(list);
    }
}
